package com.yc.sole.framework.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.yc.sole.framework.utils.node.TreeNode;

import java.util.*;

/**
 * 转换工具类
 *
 * @author yizuomin
 * @date 2021/12/19 10:28
 **/
public class TreeUtil {

    public static final String PARENT_ID = "0";

    /**
     * list转树形结构
     *
     * @param treeNodes 树节点
     * @param <T>       类型
     * @return t
     */
    public static <T extends TreeNode<T>> List<T> listToTree(Collection<T> treeNodes) {
        return listToTree(treeNodes, PARENT_ID);
    }

    /**
     * list转树形结构
     *
     * @param treeNodes 树节点
     * @param <T>       类型
     * @return t
     */
    public static <T extends TreeNode<T>> List<T> listToTree(Collection<T> treeNodes, String parentId) {
        if (CollUtil.isEmpty(treeNodes)) {
            return Collections.emptyList();
        }
        List<T> trees = new ArrayList<>();
        Set<String> ids = new HashSet<>();
        for (T node : treeNodes) {
            if (CharSequenceUtil.isBlank(node.getPid()) || parentId.equals(node.getPid())) {
                trees.add(node);
            }
            for (T it : treeNodes) {
                if (node.getNodeId().equals(it.getPid())) {
                    if (node.getChildren() == null) {
                        node.setChildren(new ArrayList<>());
                    }
                    node.getChildren().add(it);
                    ids.add(it.getNodeId());
                }
            }
        }
        if (trees.isEmpty()) {
            trees = treeNodes.stream().filter(s -> !ids.contains(s.getNodeId())).toList();
        }
        return trees;
    }
}
